/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.it;

import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipOutputStream;

import javanet.staxutils.IndentingXMLStreamWriter;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.codehaus.stax2.XMLStreamWriter2;

import ru.irenproject.ModifierList;
import ru.irenproject.Profile;
import ru.irenproject.Test;

@Singleton public final class ItOutput {
  private final ItWriterFactory fWriterFactory;

  @Inject ItOutput(ItWriterFactory writerFactory) {
    fWriterFactory = writerFactory;
  }

  public void writeFragment(ItProducer producer, OutputStream out) {
    write(producer, It.ELEM_TEST_FRAGMENT, out);
  }

  public void writeDocument(ItProducer producer, OutputStream out) {
    write(producer, It.ELEM_IREN_TEST, out);
  }

  private void write(ItProducer producer, String rootElementName, OutputStream out) {
    try {
      try (ZipOutputStream zipOut = new ZipOutputStream(out)) {
        ByteArrayOutputStream xmlOut = new ByteArrayOutputStream();
        XMLStreamWriter w = XMLOutputFactory.newInstance().createXMLStreamWriter(xmlOut);
        try {
          ((XMLStreamWriter2) w).writeRaw("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n");
          IndentingXMLStreamWriter iw = new IndentingXMLStreamWriter(w);
          try {
            w = null;
            iw.writeStartElement(rootElementName);

            producer.produce(fWriterFactory.create(iw, zipOut));

            iw.writeEndElement();
            iw.writeEndDocument();
          } finally {
            iw.close();
          }
        } finally {
          if (w != null) {
            w.close();
          }
        }

        zipOut.putNextEntry(ItWriter.createZipEntryWithFixedTime(It.IT_TEST_FILE_NAME));
        xmlOut.writeTo(zipOut);
        zipOut.closeEntry();
      }
    } catch (XMLStreamException | IOException e) {
      throw new RuntimeException(e);
    }
  }

  public byte[] modifierListToBytes(final ModifierList list) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    writeFragment(new ItProducer() {
      @Override public void produce(ItWriter out) {
        out.writeModifierList(list);
      }
    }, stream);

    return stream.toByteArray();
  }

  public byte[] profileToBytes(final Profile profile) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    writeFragment(new ItProducer() {
      @Override public void produce(ItWriter out) {
        out.writeProfile(profile);
      }
    }, stream);
    return stream.toByteArray();
  }

  public byte[] testToBytes(final Test test) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    writeDocument(new ItProducer() {
      @Override public void produce(ItWriter out) {
        out.writeTest(test);
      }
    }, stream);
    return stream.toByteArray();
  }
}
